﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Text.RegularExpressions;

namespace Pibby.Core.Feeds
{
	public static class LinkScraper
	{
		public static ReadOnlyCollection<Uri> Find(string text)
		{
			var uriList = new List<Uri>();

			// 1.
			// Find all matches in file.
			MatchCollection m1 = Regex.Matches(text, @"(<a.*?>.*?</a>)", RegexOptions.Singleline);

			// 2.
			// Loop over each match.
			foreach (Match m in m1)
			{
				string value = m.Groups[1].Value;
				
				// 3.
				// Get href attribute.
				Match m2 = Regex.Match(value, @"href=\""(.*?)\""", RegexOptions.Singleline);

				if (m2.Success)
				{
					string candidateUri = m2.Groups[1].Value;

					try
					{
						uriList.Add(Web.UriBuilder.Create(candidateUri));
					}
					catch (UriFormatException)
					{
						// can't do anything else...
					}
				}
			}

			return new ReadOnlyCollection<Uri>(uriList);
		}

	}
}
